import React, { Component, useState, useEffect } from "react";
import {
  Table,
  Input,
  InputNumber,
  Popconfirm,
  Form,
  Typography,
  Button,
  Modal,
  message,
} from "antd";
import "antd/dist/antd.css";
import { BrowserRouter as Router, Switch, Route, Link } from "react-router-dom";

import request from "../../../static/requests";
import AddDetail from "./detail/AddDetail";
import UpdateDetail from "./detail/UpdateDetail";
import { useHistory } from "react-router-dom";

const EditableCell = ({
  editing,
  dataIndex,
  title,
  inputType,
  record,
  index,
  children,
  ...restProps
}) => {
  const inputNode = inputType === "number" ? <InputNumber /> : <Input />;
  return (
    <td {...restProps}>
      {editing ? (
        <Form.Item
          name={dataIndex}
          style={{
            margin: 0,
          }}
          rules={[
            {
              required: true,
              message: `Please Input ${title}!`,
            },
          ]}
        >
          {inputNode}
        </Form.Item>
      ) : (
        children
      )}
    </td>
  );
};

const EditableTable = () => {
  const originData = [];
  const [form] = Form.useForm();
  const [data, setData] = useState(originData);
  useEffect(() => {
    banner();
  }, []);
  const banner = async () => {
    let data = await request("https://budbud.top/background/article/detail", {
      method: "GET",
      data: 1,
    });
    setData(data.data.data.reverse());
    console.log(data);
  };
  let history = useHistory();

  const [editingKey, setEditingKey] = useState("");

  const isEditing = (record) => record.id === editingKey;

  const edit = (record) => {
    form.setFieldsValue({
      name: "",
      age: "",
      image: "",
      ...record,
    });
    setEditingKey(record.id);
  };

  const cancel = () => {
    setEditingKey("");
  };

  // 修改
  const save = async (key) => {
    try {
      const newData = [...data];
      const index = newData.findIndex((item) => key === item.id);
      //表单内容
      const row = await form.validateFields();
      request("https://budbud.top/background/banner/updata", {
        method: "POST",
        data: {
          row: row,
          key: key,
        },
      }).then((response) => {
        let { data } = response;
        if (data.success == true) {
          message.success("修改成功");
        } else {
          message.error("修改失败");
        }
      });
      console.log(row);

      if (index > -1) {
        const item = newData[index];
        newData.splice(index, 1, { ...item, ...row });
        setData(newData);
        setEditingKey("");
      } else {
        newData.push(row);
        setData(newData);
        setEditingKey("");
      }
    } catch (errInfo) {
      console.log("Validate Failed:", errInfo);
    }
  };
  const columns = [
    {
      title: "id",
      dataIndex: "id",
      width: "5%",
    },
    {
      title: "标题",
      dataIndex: "title",
      width: "15%",
      editable: true,
    },
    {
      title: "摘要",
      dataIndex: "summary",
      width: "15%",
      editable: true,
    },
    {
      title: "作者",
      dataIndex: "source",
      width: "10%",
      editable: true,
    },
    {
      title: "图片",
      dataIndex: "cover",
      width: "10%",
      editable: true,
      render: (image) => <img src={image} style={{ width: "100px" }} />,
    },
    {
      title: "内容",
      dataIndex: "content",
      width: "30%",
      editable: true,
      render: (content) => (
        <div
          className="content"
          dangerouslySetInnerHTML={{ __html: content }}
        ></div>
      ),
    },
    {
      title: "操作",
      dataIndex: "operation",
      render: (_, record) => {
        const editable = isEditing(record);
        return editable ? (
          <span>
            <a
              onClick={() => {
                save(record.id);
              }}
              style={{
                marginRight: 8,
              }}
            >
              修改
            </a>
            <Popconfirm title="是否取消?" onConfirm={cancel}>
              <a style={{ marginRight: 8 }}>取消</a>
            </Popconfirm>
          </span>
        ) : (
          <div>
            <Typography.Link
              style={{ marginRight: 20 }}
              onClick={() => history.push("/updateDetail", record)}
            >
              修改
            </Typography.Link>
            <Popconfirm
              title="确认删除?"
              onConfirm={() => {
                request("https://budbud.top/background/article/detail/delete", {
                  method: "POST",
                  data: {
                    record: record.id,
                  },
                }).then((data) => {
                  banner();
                  message.success(data.data.msg);
                });
              }}
              onCancel={() => {
                console.log(1);
                message.error("取消删除");
              }}
              okText="Yes"
              cancelText="No"
            >
              <a href="#">删除</a>
            </Popconfirm>
          </div>
        );
      },
    },
  ];
  const mergedColumns = columns.map((col) => {
    if (!col.editable) {
      return col;
    }
    return {
      ...col,
      onCell: (record) => ({
        record,
        inputType: col.dataIndex === "age" ? "number" : "text",
        dataIndex: col.dataIndex,
        title: col.title,
        editing: isEditing(record),
      }),
    };
  });

  return (
    <Form form={form} component={false}>
      <Button
        type="primary"
        style={{
          marginBottom: 16,
        }}
        onClick={() => {
          history.push("/addDetail");
        }}
      >
        添加
      </Button>
      <Table
        components={{
          body: {
            cell: EditableCell,
          },
        }}
        bordered
        dataSource={data}
        columns={mergedColumns}
        rowClassName="editable-row"
        scroll={{ y: 500 }}
      />
    </Form>
  );
};
export default () => {
  return (
    <Router>
      <div>
        <Switch>
          <Route path="/updateDetail">
            <UpdateDetail />
          </Route>
          <Route path="/addDetail">
            <AddDetail />
          </Route>
          <Route path="/">
            <EditableTable />
          </Route>
        </Switch>
      </div>
    </Router>
  );
};
